﻿using System.Threading;
using Microsoft.Phone.Controls;
using CannedHeater.ViewModel;

namespace CannedHeater
{
    /// <summary>
    /// The main page of the app
    /// </summary>
    public partial class MainPage : PhoneApplicationPage
    {
        // Sets the DataContext of the StatisticsView and ControlView

        private StatisticsViewModel svm;
        private ControlViewModel cvm;

        public MainPage()
        {
            InitializeComponent();

            svm = new StatisticsViewModel();
            StatisticsView.DataContext = svm;

            cvm = new ControlViewModel();
            ControlView.DataContext = cvm;

            // Some loading is delayed to allow UI to be displayed quickly without lagging
            Thread delayStartThread = new Thread(new ThreadStart(RunInitProcedure));
            delayStartThread.Start();
        }

        /// <summary>
        /// Runs the delayed initializations
        /// </summary>
        private void RunInitProcedure()
        {
            Thread.Sleep(1500);

            Dispatcher.BeginInvoke(() => svm.LoadData()); // Must be invoked from UI thread to avoid cross-thread issues
        }

        #region Tombstoning
        // No reason to tombstone the Statistics data, since this is always stored in isolatedstorage anyway

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            // Sets the panoramaitem that was selected before tombstoning
            // Thanks to Jeff Prosise: http://www.wintellect.com/CS/blogs/jprosise/archive/2011/02/02/tombstoning-panorama-controls-in-silverlight-for-windows-phone.aspx
            if (State.ContainsKey("MainPanoramaViewIndex"))
                PanoramaView.DefaultItem = PanoramaView.Items[(int) State["MainPanoramaViewIndex"]];

            // Load the rest
            cvm.LoadTombstone(State);
        }

        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            base.OnNavigatingFrom(e);

            // Saves what panoramaitem is currently selected
            // Thanks to Jeff Prosise: http://www.wintellect.com/CS/blogs/jprosise/archive/2011/02/02/tombstoning-panorama-controls-in-silverlight-for-windows-phone.aspx
            if (State.ContainsKey("MainPanoramaViewIndex"))
                State["MainPanoramaViewIndex"] = PanoramaView.SelectedIndex;
            else
                State.Add("MainPanoramaViewIndex", PanoramaView.SelectedIndex);

            // Save the rest
            cvm.Tombstone(State);
        }
        #endregion

    }
}